package com.juhuixing.common.utils.custom;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 功能描述: 对象转换工具类
 * @author: 刘猛
 * @date: 2019/3/13 13:26
 **/
@Slf4j
public class ObjectConvertUtil {

    public static <T, E> T copyProperties(Class<T> destClassType, E orig) throws RuntimeException {
        if (orig == null) {
            log.info("转换对象为空");
            return null;
        }
        try {
            T dest = destClassType.newInstance();
            BeanUtils.copyProperties(orig, dest);
            return dest;
        } catch (Exception e) {
            log.error("转换对象出错:class={},e={}", destClassType.getName(), e);
            throw new RuntimeException("对象复制异常");
        }
    }

    public static <F, T> List<T> copyListProperties(List<F> origList, final Class<T> destClassType) {
        if (CollectionUtils.isEmpty(origList)) {
            log.info("转换对象为空");
            return null;
        }
        List<T> destList = Lists.transform(origList, new Function<F, T>() {
            @Override
            public T apply(F orig) {
                return ObjectConvertUtil.copyProperties(destClassType, orig);
            }
        });
        return Lists.newArrayList(destList);
    }

}
